
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt

from .models import Problem
import json
from django.http import JsonResponse
from .control.judge_control import Control

control = Control()
# Create your views here.
def index(request):
    return render(request,"index.html")

def all_problems(request):
    problems=Problem.objects.all().order_by('id')
    return render(request,'all_problems.html',{'problems':problems})


def problem(request, id):
    try:
        # 从数据库获取题目数据
        problem = Problem.objects.get(id=id)
        # 准备模板上下文（包含题目所有字段）
        context = {
            'id': problem.id,
            'title': problem.title,
            'star': problem.star,
            'desc': problem.desc,
            'pre_code': problem.header,
        }

        # 渲染单个题目页面
        return render(request, 'one_problems.html', context)

    except Problem.DoesNotExist:
        # 题目不存在时显示错误信息
        return render(request, 'one_problems.html', {
            'error': f'错误：编号为 {id} 的题目不存在',
            'show_error': True
        })
    except Exception as e:
        # 其他异常处理
        from django.http import HttpResponseServerError
        return HttpResponseServerError(f'服务器错误：{str(e)}')

@csrf_exempt
def judge(request, id):
    if request.method == 'POST':
        try:
            # 解析请求数据
            request_data = json.loads(request.body)
            # 调用判题控制
            return control.judge(id, request_data)
        except json.JSONDecodeError:
            return JsonResponse({'error': '请求数据格式错误'})
        except Exception as e:
            return JsonResponse({'error': f'判题错误: {str(e)}'})
    return JsonResponse({'error': '仅支持POST请求'})